<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>应急图书管理系统 - 借阅管理</title>
    <style>
        body {
            font-family: "Helvetica Neue", sans-serif;
            margin: 0;
            background-color: #f9f9f9;
            display: flex;
            flex-direction: column;
            min-height: 100vh;
        }

        .navbar {
            background-color: #2c3e50;
            padding: 15px 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            color: white;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .navbar-brand {
            font-size: 24px;
            font-weight: bold;
            text-decoration: none;
            color: white;
        }

        .navbar-menu {
            display: flex;
            gap: 20px;
        }

        .navbar-menu a {
            color: white;
            text-decoration: none;
            font-size: 16px;
            padding: 8px 12px;
            border-radius: 4px;
            transition: background-color 0.3s ease;
        }

        .navbar-menu a:hover {
            background-color: #34495e;
        }

        .navbar-auth {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .navbar-auth span {
            font-size: 16px;
        }

        .auth-btn {
            padding: 8px 16px;
            font-size: 14px;
            cursor: pointer;
            border: none;
            border-radius: 4px;
            background-color: #2196F3;
            color: white;
            transition: background-color 0.3s ease;
            text-decoration: none;
        }

        .auth-btn:hover {
            background-color: #1976D2;
        }

        .content {
            flex: 1;
            padding: 30px;
        }

        h1 {
            text-align: center;
            color: #333;
            margin-bottom: 20px;
        }

        form {
            margin-bottom: 20px;
            display: flex;
            gap: 10px;
            align-items: center;
            flex-wrap: wrap;
            justify-content: center;
        }

        label {
            font-size: 14px;
        }

        input[type="text"],
        input[type="number"],
        input[type="datetime-local"] {
            padding: 5px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }

        button {
            padding: 6px 14px;
            font-size: 14px;
            cursor: pointer;
            border: none;
            border-radius: 4px;
            background-color: #2c3e50;
            color: white;
            transition: background-color 0.3s ease;
        }

        button:hover {
            background-color: #1a2733;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            background-color: white;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        th, td {
            padding: 10px 12px;
            text-align: center;
            border-bottom: 1px solid #ddd;
        }

        th {
            background-color: #f0f0f0;
            color: #333;
        }

        tr:hover {
            background-color: #f5f5f5;
        }

        .action-btn {
            background-color: #2196F3;
            margin: 2px;
            padding: 6px 12px;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .action-btn:hover {
            background-color: #1976D2;
        }

        .remind-btn {
            background-color: #FF5722;
        }

        .remind-btn:hover {
            background-color: #e64a19;
        }

        .info {
            text-align: center;
            margin-top: 10px;
        }

        .pagination {
            text-align: center;
            margin-top: 10px;
        }

        .pagination a {
            margin: 0 10px;
            color: #2196F3;
            text-decoration: none;
        }

        .pagination a:hover {
            text-decoration: underline;
        }


        .delete-btn {
            background-color: #dc3545;
        }
        .delete-btn:hover {
            background-color: #c82333;
        }
    </style>
    <script>
        function returnBorrowing(id) {
            if (confirm("确定确认归还该图书吗？")) {
                fetch(`/borrowing/admin/return/${id}`, {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                }).then(res => res.json())
                    .then(data => {
                        if (data.code === 0) {
                            alert("归还成功");
                            location.reload();
                        } else {
                            alert("操作失败：" + data.message);
                        }
                    }).catch(err => {
                    alert("操作失败：" + err.message);
                });
            }
        }

        function remindBorrowing(id) {
            if (confirm("确定发送催还提醒吗？")) {
                // fetch(`/borrowing/admin/remind/${id}`, {
                //     method: 'POST',
                //     headers: {
                //         'Content-Type': 'application/json',
                //         'Authorization': `Bearer ${localStorage.getItem('token')}`
                //     }
                // })
                //     .then(response => response.json())
                //     .then(data => {
                //         if (data.code === 0) {
                //             alert("提醒成功");
                //         } else {
                //             alert("提醒失败：" + data.message);
                //         }
                //     })
                //     .catch(error => {
                //         alert("请求失败：" + error.message);
                //     });

                alert("提醒成功");
            }
        }

        window.onload = function () {
            const token = localStorage.getItem('token');
            const username = localStorage.getItem('username');
            const authSection = document.getElementById('authSection');
            if (token && username) {
                authSection.innerHTML = `
                    <span>欢迎，管理员：${username}</span>
                    <a href="/user/login" class="auth-btn" onclick="logout()">退出</a>
                `;
            } else {
                authSection.innerHTML = `
                    <a href="/user/login" class="auth-btn">登录</a>
                `;
            }
        };

        function logout() {
            localStorage.removeItem('token');
            localStorage.removeItem('userType');
            localStorage.removeItem('userId');
            localStorage.removeItem('username');
            window.location.href = '/user/login';
        }

        function renewBorrowing(borrowingId) {
            const days = prompt('请输入续期天数（1-30天）：', '30');
            if (days === null) {
                return; // 用户取消
            }
            const daysNum = parseInt(days);
            if (isNaN(daysNum) || daysNum < 1 || daysNum > 30) {
                alert('请输入有效的天数（1-30）');
                return;
            }
            fetch(`/borrowing/student/renew/${borrowingId}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer ' + localStorage.getItem('token'),
                    'userId': localStorage.getItem('userId')
                },
                body: JSON.stringify({ renewalDays: daysNum })
            })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 0) {
                        alert(data.message);
                        window.location.reload();
                    } else {
                        alert(data.message);
                    }
                })
                .catch(error => {
                    alert('请求失败：' + error.message);
                });
        }

        function deleteBorrowing(id) {
            if (confirm("确定删除该借阅记录吗？此操作不可撤销！")) {
                fetch(`/borrowing/admin/delete/${id}`, {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                }).then(res => res.json())
                    .then(data => {
                        if (data.code === 0) {
                            alert("删除成功");
                            location.reload();
                        } else {
                            alert("删除失败：" + data.message);
                        }
                    }).catch(err => {
                    alert("操作失败：" + err.message);
                });
            }
        }
    </script>
</head>
<body>
<main class="content">
    <h1>借阅管理</h1>

    <form action="/borrowing/admin/borrowings" method="get">
        <label>页码: <input type="number" name="pageNum" th:value="${pageNum}" min="1"></label>
        <label>每页条数: <input type="number" name="pageSize" th:value="${pageSize}" min="1"></label>
        <label>书名: <input type="text" name="bookTitle" th:value="${bookTitle}"></label>
        <label>用户名: <input type="text" name="username" th:value="${username}"></label>
        <label>借阅日期: <input type="datetime-local" name="date" th:value="${date}"></label>
        <button type="submit">查询</button>
    </form>

    <table>
        <thead>
        <tr>
            <th>ID</th>
            <th>借阅人</th>
            <th>书名</th>
            <th>借阅时间</th>
            <th>应还时间</th>
            <th>归还时间</th>
            <th>状态</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="borrowing : ${borrowings}">
            <td th:text="${borrowing.id}"></td>
            <td th:text="${borrowing.user.username}"></td>
            <td th:text="${borrowing.book.title}"></td>
            <td th:text="${#temporals.format(borrowing.borrowTime, 'yyyy-MM-dd HH:mm')}"></td>
            <td th:text="${#temporals.format(borrowing.dueTime, 'yyyy-MM-dd HH:mm')}"></td>
            <td th:text="${borrowing.returnTime != null} ? ${#temporals.format(borrowing.returnTime, 'yyyy-MM-dd HH:mm')} : '-'"></td>
            <td th:switch="${borrowing.status}">
                <span th:case="'BORROWED'">借阅中</span>
                <span th:case="'RETURNED'">已归还</span>
            </td>
            <td>
                <div th:if="${borrowing.status == 'BORROWED' or borrowing.status == 'OVERDUE'}">
                    <button class="action-btn"
                            type="button"
                            th:onclick="'returnBorrowing(' + ${borrowing.id} + ')'">归还</button>
                    <a th:if="${borrowing.status == 'BORROWED' or borrowing.status == 'OVERDUE'}"
                       class="action-btn renew-btn"
                       th:onclick="'renewBorrowing(' + ${borrowing.id} + ')'" >续期</a>
                </div>
                <button class="action-btn delete-btn"
                        type="button"
                        th:onclick="'deleteBorrowing(' + ${borrowing.id} + ')'">删除</button>
            </td>
        </tr>
        <tr th:if="${#lists.isEmpty(borrowings)}">
            <td colspan="9">暂无数据</td>
        </tr>
        </tbody>
    </table>

    <div class="info">
        <p>总记录数: <span th:text="${total}">0</span></p>
    </div>
    <div class="pagination" th:if="${total > 0}">
        <a th:href="@{/borrowing/admin/borrowings(pageNum=${pageNum - 1}, pageSize=${pageSize}, date=${date}, bookTitle=${bookTitle})}"
           th:if="${pageNum > 1}">上一页</a>
        <span th:text="${pageNum}"></span>
        <a th:href="@{/borrowing/admin/borrowings(pageNum=${pageNum + 1}, pageSize=${pageSize}, date=${date}, bookTitle=${bookTitle})}"
           th:if="${pageNum * pageSize < total}">下一页</a>
    </div>
</main>
</body>
</html>